package com.example.reactor.r2dbc.db.nativeSQL;

import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactory;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

/**
 * @author zpMeng
 * @since 6/16/2025
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class NativeSqlService {

    private final ConnectionFactory connectionFactory;

    public void executeDynamicQuery(String tableName) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        String sql = "select * from DS_AGG_427_1 where node_id <= 10000";
        log.info(sql);
        Long aLong = Flux
                .usingWhen(
                        connectionFactory.create(),
                        connection -> Flux
                                .from(connection.createStatement(sql).execute())
                                .flatMap(result -> result.map(new RecordRowMapper()))
                                .count(),
                        Connection::close
                )
                .blockLast();

        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }

}
